<?php
###############   COPYLEFT GPLv3 LICENSE   ###############
##
## JFX Version 0.2.9
## Website Management Software
## www.jfxcms.com
##
## Copyright 2009 GPLv3 - http://www.opensource.org/licenses/gpl-3.0.html
##
## Anthony Gallon
## oi_antz@hotmail.com
##
## Permission is hereby granted to any person having a copy of this software
## to freely use and modify as required so long as the copyright notices
## and branding remain intact.
##
## Full license details available at http://www.jfxcms.com/license
##
###############   COPYLEFT GPLv3 LICENSE   ###############

$userid = (int) get('userid');

$uData = $DB->fetchRow("SELECT * FROM {$CONFIG->dbprefix}iusers WHERE id = '{$userid}'");
$groups = $DB->fetchAll("SELECT group_key FROM {$CONFIG->dbprefix}iusers_to_groups WHERE user_id = '{$userid}'");
$userGroups = array();
foreach($groups as $k=>$v){
	$userGroups[] = $v['group_key'];
};

unset($groups, $k, $v);

if(Antz_IntelliForm::submitted('edit')){
    switch(post('iusersAction')){
        case 'edit':
            $userid = (int) get('userid', 0);
            if($userid == 0 || $DB->countRows($CONFIG->dbprefix.'iusers', "id = '{$userid}'")==0){
                JFX::addError($this->lang('invalid_userid').$userid);
            }else{
                // we have a valid user id
                $error = false;
                $username = post('username');
                $password = post('password');
                $busName = post('business_name');
                $email = strtolower(post('email'));
                $emailMD5 = md5(strtolower($email));
                $fName = post('first_name');
                $lName = post('last_name');
                $dob = post('dob');
                $sex = post('sex');
                $country = post('country');
                $city = (int) post('city');
                $address = post('address');
                $accessGroups = explode(',', post('access_groups'));
                $subscriber = (int) post('subscriber');

                // username
                if($username != $uData['username']){
                    $safeUsername = preg_replace('/[^a-zA-Z0-9\-_]/', '', $username);
                    if(trim($username)==''){
                        $error = true;
                        JFX::addFormError('username', $this->Lang('cannot_be_blank'));
                    }elseif($username != $safeUsername){
                        $error = true;
                        JFX::addFormError('username', $this->Lang('invalid_characters'));
                    }else{
                        if($DB->countRows($CONFIG->dbprefix.'iusers', "username = '{$safeUsername}'")>0){
                            $error = true;
                            JFX::addFormError('username', $this->Lang('already_registered'));
                        };
                    };
                };

			    // password
			    if($password != ''){
				  	// password changed
				    if(strlen($password) < 6 || strlen($password) > 20){
				        $error = true;
				        JFX::addFormError('password', $this->Lang('6-20_chars'));
				    };
			    };
			    // email
			    if($CRYPT->decrypt($uData['email_crypt']) != $email){
			    	// email is changed
				    if(trim($email)==''){
				        $error = true;
				        JFX::addFormError('email', 'Cannot be blank');
				    }else{
				        if(!JFX_Filter::checkEmail($email)){
				            $error = true;
				            JFX::addFormError('email', $this->Lang('invalid_chars'));
				        }else{
				            if($DB->countRows($CONFIG->dbprefix.'iusers', "email_md5 = '{$emailMD5}'")>0){
				                $error = true;
				                JFX::addFormError('email', $this->Lang('already_registered'));
				            };
				        };
				    };
			    };
			    // Name
			    if($this->GetConfig('be_insist_fname') && $fName == ''){
			        $error = true;
			        JFX::addFormError('first_name');
			    }
			    if($this->GetConfig('be_insist_lname') && $lName == ''){
			        $error = true;
			        JFX::addFormError('last_name');
			    }
			    // country and city
			    if($this->GetConfig('be_country_required') == 1 && ($country == 0 || $DB->countRows($CONFIG->dbprefix.'iusers_countries', "id = '{$country}'")==0)){
			        $error = true;
			        JFX::addFormError('country');
			    };
			    if($this->GetConfig('be_city_required') == 1 && ($city == 0 || $DB->countRows($CONFIG->dbprefix.'iusers_cities', "id = '{$city}'")==0)){
			        $error = true;
			        JFX::addFormError('city');
			    };

                // groups
                foreach($accessGroups as $k=>$groupKey){
                    if($DB->countRows($CONFIG->dbprefix.'iusers_groups', "keyname = '{$groupKey}'")==0){
                        unset($accessGroups[$k]);
                    };
                };
                if(count($accessGroups)==0){
                    $error = true;
                    JFX::addFormError('accessGroups');
                };

                $hashOrig = rand();
                $hash = md5($hashOrig);


               	// to other modules
				$hookParams = array(
					'error' => false,
					'errors' => array(),
					'user_data' => $uData
				);
				JFX::hook('JFX_Module_Iusers.adminEditCheck', $hookParams);
				if($hookParams['error']){
					$error = true;
					if(count($hookParams['errors'])>0){
						foreach($hookParams['errors'] as $errorMsg){
							JFX::addError($errorMsg);
						};
					};
				};


                if(!$error){

                    $emailVerification = $this->GetConfig('admin_email_verification');

                    if($CRYPT->decrypt($uData['email_crypt'])!=$email && ''!=$password){
                        // both email and password have been changed, notify the user
                        
                        $loginId = $this->GetConfig('login_id');
                        
                        if($this->GetConfig('secure_login')==1){
                            $loginUrl = str_replace('http://', 'https://', $JFX->getUrlById($loginId));
                        }else{
                            $loginUrl = $JFX->getUrlById($loginId);
                        };

                        $sitename = $LANG->get('core', 'site_title');
                        $subject = $this->Lang('password_and_email_changed');

                        if($emailVerification) $tpl = 'admin.manage.email_and_password_changed.verify.php';
                        else $tpl = 'admin.manage.email_and_password_changed.noverify.php';
                        $emailParams = array(
                            'new_email' => $email,
                            'login_url' => $loginUrl,
                            'name' => $fName.' '.$lName,
                            'email' => $email,
                            'username' => $uData['username'],
                            'password' => $password,
                            'sitename' => $sitename,
                            'email_verification_url' => $JFX->addParamsToUrl($JFX->getUrlById($this->GetConfig('email_verification_id')), array('email'=>$email, 'hash'=>$hash)),
                            'email_verification_url_htmlentities' => $JFX->addParamsToUrl($JFX->getUrlById($this->GetConfig('email_verification_id')), array('email'=>$email, 'hash'=>$hash), true),
                        );
                        foreach($emailParams as $k=>$v){
                            $SMARTY->assign('IUsers_'.$k, $v);
                        };
                        $msg = $this->ProcessEmailTemplate($tpl, $emailParams);
                        $toFrom = array(
                            'toName' => $fName.' '.$lName,
                            'toEmail' => $email
                        );
                        JFX_Email::sendRaw($subject, $msg, $toFrom, true);

                        $toFrom = array(
                            'toName' => $fName.' '.$lName,
                            'toEmail' => $CRYPT->decrypt($uData['email_crypt'])
                        );
                        JFX_Email::sendRaw($subject, $msg, $toFrom, true);

                        $uData['pass'] = $CRYPT->crypt($password);

                        if($emailVerification){
                            $uData['new_email_hash'] = $hash;
                            $uData['new_email'] = $email;
                            $uData['status'] = 2;
                        }else{
                            $uData['email_crypt'] = $CRYPT->crypt($email);
                            $uData['email_md5'] = md5(strtolower($email));
                        };

                    }else if($CRYPT->decrypt($uData['email_crypt'])!=$email){
                        // email has been changed, notify of the change

                        $loginId = $this->GetConfig('login_id');

                        if($this->GetConfig('secure_login')==1){
                            $loginUrl = str_replace('http://', 'https://', $JFX->getUrlById($loginId));
                        }else{
                            $loginUrl = $JFX->getUrlById($loginId);
                        };

                        $sitename = $LANG->get('core', 'site_title');
                        $subject = $this->lang('email_has_been_changed');
                        if($emailVerification) $tpl = 'admin.manage.email_changed.verify.php';
                        else $tpl = 'admin.manage.email_changed.noverify.php';
                        $emailParams = array(
                            'new_email' => $email,
                            'login_url' => $loginUrl,
                            'name' => $fName.' '.$lName,
                            'email' => $email,
                            'username' => $uData['username'],
                            'password' => $CRYPT->decrypt($uData['pass']),
                            'sitename' => $sitename,
                            'email_verification_url' => $JFX->addParamsToUrl($JFX->getUrlById($this->GetConfig('email_verification_id')), array('email'=>$email, 'hash'=>$hash)),
                            'email_verification_url_htmlentities' => $JFX->addParamsToUrl($JFX->getUrlById($this->GetConfig('email_verification_id')), array('email'=>$email, 'hash'=>$hash), true),
                        );
                        foreach($emailParams as $k=>$v){
                            $SMARTY->assign('IUsers_'.$k, $v);
                        };
                        $msg = $this->ProcessEmailTemplate($tpl, $emailParams);
                        $toFrom = array(
                            'toName' => $fName.' '.$lName,
                            'toEmail' => $email
                        );
                        JFX_Email::sendRaw($subject, $msg, $toFrom, true);
                        $toFrom = array(
                            'toName' => $fName.' '.$lName,
                            'toEmail' => $CRYPT->decrypt($uData['email_crypt'])
                        );

                        JFX_Email::sendRaw($subject, $msg, $toFrom, true);

                        if($emailVerification){
                            $uData['new_email_hash'] = $hash;
                            $uData['new_email'] = $email;
                            $uData['status'] = 2;
                        }else{
                            $uData['email_crypt'] = $CRYPT->crypt($email);
                            $uData['email_md5'] = md5(strtolower($email));
                        };

                    }else if(''!=$password){
                        // password has been changed, notify of the change

                        $loginId = $this->GetConfig('login_id');

                        if($this->GetConfig('secure_login')==1){
                            $loginUrl = str_replace('http://', 'https://', $JFX->getUrlById($loginId));
                        }else{
                            $loginUrl = $JFX->getUrlById($loginId);
                        };

                        $sitename = $LANG->get('core', 'site_title');
                        $subject = $this->Lang('password_changed');
                        $tpl = 'admin.manage.password_changed.php';
                        $emailParams = array(
                            'login_url' => $loginUrl,
                            'name' => $fName.' '.$lName,
                            'email' => $email,
                            'username' => $uData['username'],
                            'password' => $password,
                            'sitename' => $sitename,
                            'email_verification_url' => $JFX->addParamsToUrl($JFX->getUrlById($this->GetConfig('email_verification_id')), array('email'=>$email, 'hash'=>$hash)),
                            'email_verification_url_htmlentities' => $JFX->addParamsToUrl($JFX->getUrlById($this->GetConfig('email_verification_id')), array('email'=>$email, 'hash'=>$hash), true),
                        );
                        foreach($emailParams as $k=>$v){
                            $SMARTY->assign('IUsers_'.$k, $v);
                        };
                        $msg = $this->ProcessEmailTemplate($tpl, $emailParams);
                        $toFrom = array(
                            'toName' => $fName.' '.$lName,
                            'toEmail' => $CRYPT->decrypt($uData['email_crypt'])
                        );
                        JFX_Email::sendRaw($subject, $msg, $toFrom, true);

                        $uData['pass'] = $CRYPT->crypt($password);
                    }
                    $uData['username'] = $username;
                    $uData['first_name'] = $fName;
                    $uData['last_name'] = $lName;
                    $uData['dob'] = $dob;
                    $uData['sex'] = $sex;
                    $uData['country'] = $country;
                    $uData['city'] = $city;
                    $uData['address'] = $address;
                    $uData['email_subscriber'] = $subscriber;
                    $uData['business_name'] = $busName;

//$DB->showErrors(true);
//$DB->debug(true);
                    $DB->update($CONFIG->dbprefix.'iusers', $uData, "id = '{$uData['id']}'");

//$DB->showErrors(false);
//$DB->debug(false);

                    $DB->delete($CONFIG->dbprefix.'iusers_to_groups', "user_id = '{$userid}'");
                    foreach($accessGroups as $k=>$v){
                        $v = preg_replace('/[^a-zA-Z0-9_\-]/', '', $v);
                        if($DB->countRows($CONFIG->dbprefix.'iusers_groups', "keyname = '{$v}'")==0) continue;
                        $DB->insert($CONFIG->dbprefix.'iusers_to_groups', array('group_key'=>$v, 'user_id'=>$userid));
                    };

					// to other modules
        			$uData['email'] = $email;
        			$uData['password'] = $password;
					$hookParams = array('user_data' => $uData);
					JFX::hook('JFX_Module_Iusers.adminEditProcess', $hookParams);

                    JFX::addSuccess($this->Lang('config_success'));
                }
            }

        break;
    }
}





if($userid > 0){


	$accessGroups = $DB->fetchAll("SELECT title, keyname FROM {$CONFIG->dbprefix}iusers_groups ORDER BY title ASC");

	// make our group selector
	$groupOptions = array('0'=>$this->Lang('add_remove'));
	foreach($accessGroups as $k=>$v){
		$groupOptions[$v['keyname']] = $v['title'].' ['.$v['keyname'].']';
	}

    unset($accessGroups);

	$groupFields = array(
		'type' => 'select',
		'name' => 'groupSel',
		'value' => $this->Lang('add_remove'),
		'label' => '',
		'options' => $groupOptions,
		'extra' => array(
			array(
				'command' => 'addJsEvent',
				'params' => array(
					"'onchange'",
					"'IUsers_Admin.new_addGroup(\'accessGroups\', this)'"
				)
			)
		)
	);

	$groupSel = JFX::makeFormComponent($groupFields, false, false);

	$countries = $DB->fetchAll("SELECT id, title FROM ".$CONFIG->dbprefix.'iusers_countries ORDER BY title ASC');
	if(post('country')=='') $country = $this->GetConfig('default_country');
	else $country = post('country');

	$countryOptions = array();
	foreach($countries as $k=>$v){
		$countryOptions[$v['id']] = $v['title'];
	}
	unset($countries);
	
	$minPopulation = (int) $this->GetConfig('cities_min_population');
	$country = strtolower($country);
	$cities = $DB->fetchAll("SELECT id, title FROM {$CONFIG->dbprefix}iusers_cities WHERE LOWER(country_id) = '{$country}' AND population > {$minPopulation} ORDER BY title ASC");
	$cityOptions = array();
	foreach($cities as $k=>$v){
		$cityOptions[$v['id']] = $v['title'];
	}
    unset($cities);

	// gonna define the form fields as an array because other modules can add their fields to it (See JFX::hook())
	$formFields = array(
	   array(
        'type' => 'text',
        'name' => 'username',
        'value' => post('username', $uData['username']),
        'label' => $this->Lang('username')
       ),
		array(
			'type' => 'hidden',
			'name' => 'iusersAction',
			'value' => 'edit',
			'label' => ''
		),
		array(
			'name' => 'business_name',
			'type' => 'text',
			'value' => post('business_name', $uData['business_name']),
			'label' => $this->Lang('business_name')
		),
		array(
			'name' => 'email',
			'value' => post('email', $CRYPT->decrypt($uData['email_crypt'])),
			'type' => 'text',
			'label' => $this->Lang('email')
		),
		array(
			'name' => 'password',
			'value' => post('password'),
			'type' => 'password',
			'label' => $this->Lang('password')
		),
		array(
			'name' => 'first_name',
			'value' => post('first_name', $uData['first_name']),
			'type' => 'text',
			'label' => $this->Lang('first_name')
		),
		array(
			'name' => 'last_name',
			'value' => post('last_name', $uData['last_name']),
			'type' => 'text',
			'label' => $this->Lang('last_name')
		),
		array(
			'name' => 'dob',
			'value' => post('dob', $uData['dob']),
			'type' => 'text',
			'label' => $this->Lang('dob')
		),
		array(
			'name' => 'sex',
			'value' => post('sex', $uData['sex']),
			'type' => 'select',
			'label' => $this->Lang('sex'),
			'options' => array(
				'0' => $this->Lang('both'),
				'm' => $this->Lang('male'),
				'f' => $this->Lang('female')
			)
		),

		array(
			'type' => 'textarea',
			'name' => 'address',
			'value' => post('address', $uData['address']),
			'label' => $this->Lang('address'),
			'class' => 'small'
		),
		array(
			'name' => 'country',
			'value' => post('country', $uData['country']),
			'type' => 'select',
			'label' => $this->Lang('country'),
			'options' => $countryOptions,
			'id' => 'countrySel',
			'extra' => array(
					0 => array(
					'command' => 'addJsEvent',
					'params' => array(
						"'onchange'",
						"'IUsers_Places.getCitiesForCountry(\'{$CONFIG->baseUrl}\', this, \'citySel\')'"
					)
				)
			)
		),
		array(
			'name' => 'city',
			'value' => post('city'),
			'type' => 'select',
			'label' => $this->Lang('city', $uData['city']),
			'options' => $cityOptions,
			'id' => 'citySel'
		),
		array(
			'type' => 'textarea',
			'name' => 'access_groups',
			'value' => post('access_groups', implode(',', $userGroups)),
			'label' => $this->Lang('member_of_groups'),
			'aftertext' => $groupSel->render(),
			'id' => 'accessGroups',
			'class' => 'grayed-out small',
			'extra' => array(
				array(
					'command' => 'addJsEvent',
					'params' => array(
						"'onfocus'",
						"'blur(this)'"
					)
				)
			)
		)
	);


	// implement the hook to get extra form fields from other modules
	$hookParams = array('form_fields' => $formFields);
	JFX::hook('JFX_Module_Iusers.adminEditForm', $hookParams);
	$formFields = $hookParams['form_fields'];
	unset($newParams);



	// prepare the structure for auto form generation
	$blocks = array(
		0 => array(
			'type' => 'full',
			'fieldsets' => array(
				0 => array(
					'legend' => $this->Lang('register_legend'),
					'side' => 'left',
					'fields' => $formFields
				)
			)
		)
	);


	$form = JFX::makeForm($blocks, 'edit');

	$form->addSubmit($this->Lang('submit'));

	$SMARTY->assign('newForm', $form->render());








/*
	// build the form for editing member details
	$accessGroups = $DB->fetchAll("SELECT * FROM {$CONFIG->dbprefix}iusers_groups");
	$ags = $DB->fetchAll("SELECT * FROM {$CONFIG->dbprefix}iusers_to_groups WHERE user_id = '{$userid}'");
	$agss = array();
	foreach($ags as $k=>$v){
	    $agss[] = $v['group_key'];
	};
	$ags = implode(',', $agss);

	$countries = $DB->fetchAll("SELECT * FROM ".$CONFIG->dbprefix.'iusers_countries ORDER BY title ASC');
	if(trim($uData['country'])=='') $uData['country'] = $this->GetConfig('default_country');
	$cities = $DB->fetchAll("SELECT * FROM {$CONFIG->dbprefix}iusers_cities WHERE country_id = '{$uData['country']}' ORDER BY title ASC");

	$form = JFX::newObject('JFX_Form', __FILE__);
	$form->setAction($actionUrls['edit'].'&amp;userid='.$userid);
	$block = $form->add('full');
	$fs = $block->add($this->Lang('user_details'));
	$fs->addInput('hidden', 'iusersAction', '', 'edit');
	$pwd = $fs->addInput('password', 'mg_editPassword', $this->Lang('password'), '');
	$pwd->addParameter('autocomplete', 'off');

	// access groups
	$sel = JFX::newObject('JFX_Form_Components_Select', array('mg_editGroups', $this->Lang('add_remove')));
	$sel->add($this->Lang('add_remove'), '0');
	foreach($accessGroups as $k=>$v){
	   $sel->add($v['title'].' ['.$v['keyname'].']', $v['keyname']);
	};
	$ag = $fs->addInput('text', 'mg_editAccessGroups', $this->Lang('member_of_groups'), post('new_accessGroups', $ags));
	$ag->addJsEvent('onfocus', 'this.blur()');
	$ag->addClass('grayed-out');
	echo '<style type="text/css">.grayed-out{background-color: #EEE;}</style>';
	$sel->addJsEvent('onchange', 'IUsers_Admin.new_addGroup(\''.$ag->getId().'\', this)');
	$sel->showLabel(false);
	$sel->setWrap(false);
	$ag->addAftertext($sel->render());

	$fs->addInput('text', 'mg_busname', $this->Lang('business_name'), $uData['business_name']);
	$e = $fs->addInput('text', 'mg_editEmail', $this->Lang('email'), $CRYPT->decrypt($uData['email_crypt']));
	$e->addParameter('autocomplete', 'off');
	$fs->addInput('text', 'mg_editFName', $this->Lang('first_name'), $uData['first_name']);
	$fs->addInput('text', 'mg_editLName', $this->Lang('last_name'), $uData['last_name']);
	$fs->addInput('text', 'mg_editDob', $this->Lang('dob'), $uData['dob']);
	$sex = $fs->addSelect('mg_editSex', $this->Lang('sex'), $uData['sex']);
	$sex->add($this->Lang('both'), '0');
	$sex->add($this->Lang('male'), 'm');
	$sex->add($this->Lang('female'), 'f');
	$chk = $fs->addCheckboxGroup('chk');
	$chk->add('subscriber', $this->Lang('subscribe_to_newsletters'), '1', $uData['email_subscriber']);

	$ctrySel = $fs->addSelect('mg_editCountry', $this->Lang('country'), post('mg_editCountry', $uData['country']));
	$ctrySel->add($this->Lang('please_select'), '0');
	//var_dump($countries);exit;
	foreach($countries as $k=>$v){
	    $ctrySel->add($v['title'], $v['id']);
	};
	$citySel = $fs->addSelect('mg_editCity', $this->Lang('city'), post('mg_editCity', $uData['city']));
	$citySel->add($this->Lang('please_select'), '0');
	foreach($cities as $k=>$v){
	    $citySel->add($v['title'], $v['id']);
	};
	$ctrySel->addJsEvent('onchange', 'IUsers_Places.getCitiesForCountry(\''.$this->config['root_url'].'\', this, \''.$citySel->getId().'\')');

	$fs->addInput('textarea', 'mg_editAddress', $this->Lang('address'), $uData['address'])->addClass('address');


	$fs->addInput('submit', 'submitBtn', '&nbsp;', $this->Lang('update'));

*/

	$SMARTY->assign('mg_editForm', $form->render());
	$SMARTY->assign('userid', $userid);
	$SMARTY->assign('uData', $uData);


}

echo $this->fetchTemplate('admin.manage.php');


